package com.cskaoyan.gateway.controller.shopping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.order.OrderCoreService;
import com.mall.order.OrderQueryService;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dto.CreateOrderRequest;
import com.mall.order.dto.CreateOrderResponse;
import com.mall.user.intercepter.TokenIntercepter;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @Author: ZaiRiChangYe
 * @Date: 2020/5/12 21:04
 * @Description:
 */
@RestController
@RequestMapping("/shopping")
public class OrderController {

    @Reference(check = false)
    private OrderCoreService orderCoreService;

    @Reference(check = false)
    private OrderQueryService orderQueryService;

    /**
     * 创建订单
     */
    @PostMapping("/order")
    public ResponseData order(@RequestBody CreateOrderRequest orderRequest, HttpServletRequest request, HttpServletResponse response){
        String userInfo = (String) request.getAttribute(TokenIntercepter.USER_INFO_KEY);
        JSONObject object = JSON.parseObject(userInfo);
        long uid = Long.parseLong(object.get("uid").toString());
        orderRequest.setUserId(uid);
        // 设置uniqueKey
        orderRequest.setUniqueKey(UUID.randomUUID().toString());
        CreateOrderResponse orderResponse = orderCoreService.createOrder(orderRequest);

        if (orderResponse.getCode().equals(OrderRetCode.SUCCESS.getCode())){
            return new ResponseUtil<>().setData(orderResponse.getOrderId());
        }
        return new ResponseUtil<>().setErrorMsg(orderResponse.getMsg());
    }
}
